$(function() {
	$.init();
	var ordersCache = [];
	$(document).on('click', '.j-look', lookHandle);
	renderList();
	
	function renderList() {
		fetchList(function (list) {
			ordersCache = list;
			var html = list.reduce(function(memo, item) {
				return memo + getItemHtml(item);
			}, '');
			if (!html) {
				html = '<div>暂无订单列表</div>';
			}
			$('.content ul').html(html);
		});
	}

	function fetchList (callback) {
		$.ajax({
			url: HOST + '/api/order/list',
			data: {
				openid: SELFID
			},
			success: function(res) {
				callback && callback(res.content);
			}
		});
	}

	function getItemHtml (data) {
		return '<li class="order-item j-look">\
					<div class="item-header">订单编号：'+data.orderCode+'<div class="item-status">'+{10:'待支付',20:'已支付',30:'已完成',40:'关闭',50:'退款中',60:'已退款',25:'已发货'}[data.orderStatus]+'</div></div>\
					<div class="item-content">'+data.skus.reduce(function(memo, item){
						return memo + '<img src="' + item.skuImage + '">';
					}, '')+(data.skus.length==1?('<span>'+data.skus[0].skuName+'</span>'):'')+'</div>\
					<div class="item-footer">共'+data.skus.length+'件商品，实付款：￥'+data.totalAmount+'</div>\
				</li>';
	}

	function lookHandle (e) {
		var data = ordersCache[$(e.currentTarget).index()];
		if (data.orderStatus == 10) {
			var details = [{
				sku_image: data.skuImage,
				sku_name: data.skuName,
				current_price: data.price,
				qty: data.qty,
				sku_code: data.skuCode
			}];
			sessionStorage.setItem('status', data.orderStatus);
			sessionStorage.setItem('orderCode', data.orderCode);
			sessionStorage.setItem('details', JSON.stringify(details));
			sessionStorage.setItem('total', data.price * data.qty);
			window.location = './product_sure.html?from=order';
		}else {
			window.location = './order_info.html?orderCode=' + data.orderCode;
		}
	}
})
